﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Content.Web;

namespace Content
{
    public partial class App : Application
    {

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                var unitID = new Guid(Application.Current.Host.InitParams["UnitID"]);
                var contentDomainContext = new ContentDomainContext();
                var queryUnit = contentDomainContext.GetUnitQuery(unitID);
                var loadOpUnit = contentDomainContext.Load<Unit>(queryUnit);

                loadOpUnit.Completed += (sender2, e2) =>
                {
                    if (loadOpUnit.HasError)
                    {
                        this.RootVisual = new DbUnitDetailsRight(loadOpUnit.Error.Message, loadOpUnit.Error.StackTrace);
                    }
                    else if (loadOpUnit.Entities.Count() == 0)
                    {
                        this.RootVisual = new DbUnitDetailsRight("Unit not found", string.Format("No unit found for ID {0}.", unitID));
                    }
                    else
                    {
                        var unit = loadOpUnit.Entities.First();

                        if ((bool)unit.HasContentRows)
                        {
                            var queryRows = contentDomainContext.GetContentRowsForUnitQuery(unitID);
                            var loadOpRows = contentDomainContext.Load<ContentRow>(queryRows);

                            loadOpRows.Completed += (sender3, e3) =>
                            {
                                if (loadOpRows.HasError)
                                {
                                    this.RootVisual = new DbUnitDetailsRight(loadOpUnit.Error.Message, loadOpUnit.Error.StackTrace);
                                }
                                else
                                {
                                    this.RootVisual = new DbUnitContentRows(unit);
                                }
                            };
                        }
                        else
                        {
                            var queryPoints = contentDomainContext.GetBulletPointsForUnitQuery(unitID);
                            var loadOpPoints = contentDomainContext.Load<BulletPoint>(queryPoints);

                            loadOpPoints.Completed += (sender3, e3) =>
                            {
                                if (loadOpPoints.HasError)
                                {
                                    this.RootVisual = new DbUnitDetailsRight(loadOpUnit.Error.Message, loadOpUnit.Error.StackTrace);
                                }
                                else
                                {
                                    this.RootVisual = RandomExtension.LoadRandomUnit(unit, InstantiateLeft, InstantiateRight, InstantiateTop);
                                }
                            };
                        }
                    }
                };

            }
            catch (Exception ex)
            {
                this.RootVisual = new DbUnitDetailsRight(ex.Message, ex.StackTrace);
            }
        }

        private DbUnit InstantiateRight(Unit unit)
        {
            return new DbUnitDetailsRight(unit);
        }

        private DbUnit InstantiateLeft(Unit unit)
        {
            return new DbUnitDetailsLeft(unit);
        }

        private DbUnit InstantiateTop(Unit unit)
        {
            return new DbUnitDetailsTop(unit);
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
